package com.trimps.wifi.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.trimps.wifi.common.Paginator;
import com.trimps.wifi.pojo.Device;
import com.trimps.wifi.pojo.DeviceCfg;
import com.trimps.wifi.service.IDevManagerService;
import com.trimps.wifi.service.IDevService;

@Controller
@RequestMapping(value = "dev/")
public class DeviceController extends BaseController {
    private static final Logger logger = Logger.getLogger(DeviceController.class);

    @Autowired
    private IDevService devService;
    @Autowired
    private IDevManagerService devManagerService;

    /**
     * 接受设备推送端消息
     * @param req
     * @param resp
     */
    @RequestMapping(value = "manager")
    public void manager(HttpServletRequest req, 
			HttpServletResponse resp) {
    	try {
			InputStream is = req.getInputStream();
			
			StringBuilder sb = new StringBuilder();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1 ) {
				for (int i = 0; i < buffer.length; i++) {
					buffer[i] ^= 0xAA;
				}
				sb.append(new String(buffer, 0, len, "UTF-8"));
			}
			is.close();
			devManagerService.handle(sb.toString(), req.getRemoteAddr(), resp.getOutputStream());
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} 
    }

	@RequestMapping(value = "list")
    public String userlist(Paginator page,
                    ModelMap map) {
        if(page == null || page.getTotalItemCount() == -1){
            page = new Paginator();
            page.setShowItemCount(8);
            int userCount = devService.getDevCount();
            page.setTotalItemCount(userCount);
        }
        List<Device> devices = devService.getAllDevice(page.getStart(), page.getOffset());
        map.put("devices", devices);
        map.put("page", page);
        return "dev/list";
    }
	
	@RequestMapping(value = "getAllDevices",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getAllDevices(Paginator page)  {
     // 返回用
        Map<String, Object> map = new HashMap<String, Object>();
        List<Device> devices = devService.getAllDevice(0, Integer.MAX_VALUE);
        map.put("devices", devices);
        return map;
    }
	
	@RequestMapping(value = "detail")
	public String detail(@RequestParam(value = "id") int id,
            ModelMap map) {
		Device dev = devService.getDevById(id);
		if(dev != null) {
			DeviceCfg cfg = devService.getDevCfgByDevNo(dev.getDevNo());
			map.put("cfg", cfg);
		}
		map.put("dev", dev);
		return "dev/detail";
	}
	
	@RequestMapping(value = "add")
	public String addPage() {
		return "dev/detail";
	}
	
	@RequestMapping(value = "del")
	public String del(@RequestParam(value = "devNo") String devNo) {
		devService.delByNo(devNo);
		logger.info("delete devive : "+devNo);
		return "redirect:./list";
	}
	
	@RequestMapping(value = "save", method=RequestMethod.POST)
	public String save(Device dev ,DeviceCfg cfg) {
		int rst1 = devService.saveDevice(dev);
		int rst2 = devService.saveDeviceCfg(cfg);
		System.out.println(rst1+" : "+rst2);
		return "redirect:./list";
	}
    
    
    @ResponseBody
    @RequestMapping(value = "saveDevCfg")
    public Map<String, Object> saveDevCfg(DeviceCfg cfg) {
    	devService.editDevCfg(cfg);
        return super.buildSuccessMsg("保存成功！");
    }
}
